﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TC.SSO.Server.Core
{
    public abstract class BaseController : Controller
    {
        protected bool IsMobile
        {
            get
            {
                return HttpContext.Request.Browser.IsMobileDevice;
            }
        }

        public ActionResult JsonResult(bool success, string message, object data)
        {
            return this.Json(new
            {
                success = success,
                message = message,
                data = data
            });
        }

        public ActionResult JsonOkResult(object data)
        {
            return this.JsonResult(true, null, data);
        }

        public ActionResult JsonOkResult()
        {
            return this.JsonOkResult(0);
        }

        public ActionResult JsonErrorResult(string message)
        {
            return this.JsonResult(false, message, null);
        }

        public string[] RemovteIps()
        {
            List<string> ips = new List<string>();
            //如果客户端使用了代理服务器，则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
            string userHostAddress = "";
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                userHostAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            }
            //否则直接读取REMOTE_ADDR获取客户端IP地址
            if (!string.IsNullOrEmpty(userHostAddress))
            {
                ips.Add(userHostAddress);
            }
            userHostAddress = Request.ServerVariables["REMOTE_ADDR"];
            //前两者均失败，则利用Request.UserHostAddress属性获取IP地址，但此时无法确定该IP是客户端IP还是代理IP
            if (!string.IsNullOrEmpty(userHostAddress))
            {
                ips.Add(userHostAddress);
            }
            return ips.ToArray();
        }
    }
}